package com.anlu.concurrent.ch7;

import com.anlu.concurrent.utils.SleepTools;

/**
 * <p>
 * Description:演示普通死锁
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/10/29 13:46
 */
public class NormalDeadLock {

    /**
     * 演示第一个锁
     */
    private static Object valueFirst = new Object();
    /**
     * 演示第二个锁
     */
    private static Object valueSecond = new Object();


    /**
     * 先拿第一个锁，再拿第二个
     * @throws InterruptedException
     */
    private static void firstToSecond()throws InterruptedException{
        String threadName = Thread.currentThread().getName();
        synchronized (valueFirst){
            System.out.println(threadName+" get first");
            SleepTools.ms(100);
            synchronized (valueSecond) {
                System.out.println(threadName+" get second");
            }
        }
    }

    private static void SecondToFirst()throws InterruptedException{
        String threadName = Thread.currentThread().getName();
        synchronized (valueFirst) {
            System.out.println(threadName+" get first");
            SleepTools.ms(100);
            synchronized (valueSecond) {
                System.out.println(threadName+" get second");
            }
        }
    }

    //执行先拿第二个锁，再拿第一个锁
    private static class TestThread extends Thread{

        private String name;

        public TestThread(String name) {
            this.name = name;
        }

        @Override
        public void run(){
            Thread.currentThread().setName(name);
            try {
                SecondToFirst();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread.currentThread().setName("TestDeadLock");
        TestThread testThread = new TestThread("SubTestThread");
        testThread.start();
        try{
            //先拿第一个锁，再拿第二个锁
            firstToSecond();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

}
